<template>
	<view class="content">
		<view style="width: 100%;height: 100vh;">
			<view v-for="(item,index) in list" v-bind:key="index" style="width: 100%;display: flex;">
				<view v-if="item.sender == 'user'" style="width: 100%;display: flex;justify-content: flex-end;padding: 5px;">
					<view  style="float:right;background-color: #F0AD4E; padding: 10px;">{{item.content}}</view>
				</view>
				<view v-else style="width: 100%;display: flex;justify-content: flex-start;padding: 5px;">
					<view style="background-color: #FFFFFF;padding: 10px;">{{item.content}}</view>
				</view>
			</view>
		</view>
		<view style="position: fixed;height: 90px;width: 100%;bottom: 0px;background-color: #999999;display: flex;">
			<input style="width: 70%;height: 44px;background-color: #F1F1F1;" placeholder="输入文本" v-model="message"></input>
			<button style="height: 44px;width: 30%;" type="primary" @click="addMessage">发送</button>
		</view>
	</view>
</template>

<script>
	var _this = undefined
	
	export default {
		data() {
			return {
				message: '',
				list: []
			}
		},
		onLoad() {
			_this = this
			this.connectSocketInit()
		},
		methods: {
			addMessage(){
				let data = {
					sender: "user",
					content:this.message
				}
				this.list.push(data)
				this.message = ''
			},
			pushMessage(key, data) {
				//发送消息
				var protobuf = require('../websocket/weichatPb/protobuf.js'); //引入protobuf模块
				var awesomeConfig = require('../websocket/SentBodyData.js');
				var AwesomeRoot = protobuf.Root.fromJSON(awesomeConfig);
				var AwesomeMessage = AwesomeRoot.lookupType("SentBody");
				var payload = {
					key: key,
					timestamp: new Date().getTime(),
					data: data
				};
				var message = AwesomeMessage.create(payload);

				var buffer = AwesomeMessage.encode(message).finish();
				// var deMessage = AwesomeMessage.decode(buffer);

				let protobufdata = new Uint8Array(buffer.length + 1);
				protobufdata[0] = 3;
				protobufdata.set(buffer, 1);
				return protobufdata
			},
			getMessageData(res) {
				
				let data = new Uint8Array(res.data);
				let type = data[0];
				let body = data.subarray(1, data.length);
				console.log('消息类型',type) 
				if (type == 1) {
					console.log('心跳消息', body)
					let PONG_BODY = new Uint8Array([80, 79, 78, 71]);
					let pong = new Uint8Array(PONG_BODY.byteLength + 1);
					pong[0] = 1;
					pong.set(PONG_BODY, 1);
					_this.socketTask.send({
						data: pong,
						async success() {
							console.log("心跳消息发送成功");
						},
					});
				} else if (type == 2) {
					var protobuf = require('../websocket/weichatPb/protobuf.js'); //引入protobuf模块
					var awesomeConfig = require('../websocket/MessageData.js');
					var AwesomeRoot = protobuf.Root.fromJSON(awesomeConfig);
					var AwesomeMessage = AwesomeRoot.lookupType("Message");
					var message = AwesomeMessage.decode(body);
					console.log('收到Message消息', message)
					let listdata = {
						sender: message.sender,
						content:message.content
					}
					_this.list.push(listdata)
					// return message
				} else {
					var protobuf = require('../websocket/weichatPb/protobuf.js'); //引入protobuf模块
					var awesomeConfig = require('../websocket/ReplyBodyData.js');
					var AwesomeRoot = protobuf.Root.fromJSON(awesomeConfig);
					var AwesomeMessage = AwesomeRoot.lookupType("ReplyBody");
					var message = AwesomeMessage.decode(body);
					console.log('收到ReplyBody消息', message)
					if (parseInt(message.code) == 200 && message.key == "client_bind") {
						uni.showToast({
							title: '登录成功'
						})
					}
					// return message
				}
			},

			connectSocketInit() {
				// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
				this.socketTask = uni.connectSocket({
					// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
					url: "ws://192.168.1.123:34567/",
					success(data) {
						console.log("websocket连接成功");
					},
				});
				// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
				this.socketTask.onOpen((res) => {
					console.log("WebSocket连接正常打开中...！");
					// 注：只有连接正常打开中 ，才能正常成功发送消息
					//像服务端发送登录信息
					console.log()
					let data = {
						appVersion: '1.0.0',
						channel: 'wxapp',
						deviceId: uni.getSystemInfoSync().deviceId, //设备id
						deviceName: uni.getSystemInfoSync().model + ' ' +uni.getSystemInfoSync().system,  //手机以及版本
						language: uni.getSystemInfoSync().language,//手机语言
						osVersion: uni.getSystemInfoSync().version,//微信版本
						packageName: 'com.farsunset.cim',
						uid: '小程序999999'
					}
					let login = _this.pushMessage('client_bind', data)

					this.socketTask.send({
						data: login,
						async success() {
							console.log("消息发送成功");
						},
					});
					// 注：只有连接正常打开中 ，才能正常收到消息
					this.socketTask.onMessage((res) => {
						_this.getMessageData(res)
					});
				})
				// 这里仅是事件监听【如果socket关闭了会执行】
				this.socketTask.onClose(() => {
					console.log("WebSocket已经被关闭了")
				})

			}
		}
	}
</script>

<style>
	.content {
		width: 100%;
		display: flex;
		flex-direction: column;
		background-color: #F1F1F1;
		min-height:100%
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>
